package com.jscloud.bigdata.flink.datasource;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class StreamSocketJava {
        public static void main(String[] args) throws Exception {
                StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();
                DataStreamSource<String> socketStream = executionEnvironment.socketTextStream("bigdata01", 9999);
                //对获取到的数据按照空格进行切分
                SingleOutputStreamOperator<String> words = socketStream.flatMap(new FlatMapFunction<String, String>() {
                        @Override
                        public void flatMap(String value, Collector<String> out) throws Exception {
                                String[] wordArray = value.split(" ");
                                for (String word : wordArray) {
                                        out.collect(word);
                                }

                        }
                });
                Tuple2<String, Integer> tuple2 = new Tuple2<>();
                //每个单词出现一次记作1次
                SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = words.map(new MapFunction<String, Tuple2<String, Integer>>() {
                        @Override
                        public Tuple2<String, Integer> map(String value) throws Exception {
                                tuple2.setFields(value, 1);
                                return tuple2;
                        }
                });
                //对数据按照key进行分组
                KeyedStream<Tuple2<String, Integer>, String> groupByKey = wordAndOne.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
                        @Override
                        public String getKey(Tuple2<String, Integer> value) throws Exception {
                                return value.f0;
                        }
                });
                //对出现的数据进行统计求和
                SingleOutputStreamOperator<Tuple2<String, Integer>> resultOutput = groupByKey.sum(1);
                resultOutput.print();
                executionEnvironment.execute();
        }
}